using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using WMSSystem.YSL.Dto.LoginDto;

namespace WMSSystem.YSL
{
    /// <summary>
    /// JWT令牌辅助工具类
    /// 优化后只处理必要的用户信息：id、userName、phoneNumber、realName
    /// </summary>
    public static class JwtTokenHelper
    {
        /// <summary>
        /// 从JWT令牌中获取用户信息
        /// </summary>
        /// <param name="token">JWT令牌字符串</param>
        /// <returns>用户信息DTO</returns>
        public static LoginResultDto GetUserFromToken(string token)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var jwtToken = tokenHandler.ReadJwtToken(token);

                // 从令牌中提取用户信息（只包含必要信息）
                var id = jwtToken.Claims.FirstOrDefault(x => x.Type == "id")?.Value;
                var userName = jwtToken.Claims.FirstOrDefault(x => x.Type == "userName")?.Value;
                var phoneNumber = jwtToken.Claims.FirstOrDefault(x => x.Type == "phoneNumber")?.Value;
                var realName = jwtToken.Claims.FirstOrDefault(x => x.Type == "realName")?.Value;

                if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(userName))
                {
                    return null;
                }

                return new LoginResultDto
                {
                    Id = Guid.Parse(id),
                    UserName = userName,
                    PhoneNumber = phoneNumber ?? "",
                    RealName = realName ?? "",
                    StatusCode = 200,
                    Message = "令牌有效"
                };
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 从JWT令牌中获取用户ID
        /// </summary>
        /// <param name="token">JWT令牌字符串</param>
        /// <returns>用户ID</returns>
        public static string GetUserIdFromToken(string token)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var jwtToken = tokenHandler.ReadJwtToken(token);
                return jwtToken.Claims.FirstOrDefault(x => x.Type == "id")?.Value;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 从JWT令牌中获取用户名
        /// </summary>
        /// <param name="token">JWT令牌字符串</param>
        /// <returns>用户名</returns>
        public static string GetUserNameFromToken(string token)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var jwtToken = tokenHandler.ReadJwtToken(token);
                return jwtToken.Claims.FirstOrDefault(x => x.Type == "userName")?.Value;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 从JWT令牌中获取真实姓名
        /// </summary>
        /// <param name="token">JWT令牌字符串</param>
        /// <returns>真实姓名</returns>
        public static string GetRealNameFromToken(string token)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var jwtToken = tokenHandler.ReadJwtToken(token);
                return jwtToken.Claims.FirstOrDefault(x => x.Type == "realName")?.Value;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 从JWT令牌中获取手机号
        /// </summary>
        /// <param name="token">JWT令牌字符串</param>
        /// <returns>手机号</returns>
        public static string GetPhoneNumberFromToken(string token)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var jwtToken = tokenHandler.ReadJwtToken(token);
                return jwtToken.Claims.FirstOrDefault(x => x.Type == "phoneNumber")?.Value;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 检查JWT令牌是否过期
        /// </summary>
        /// <param name="token">JWT令牌字符串</param>
        /// <returns>是否过期</returns>
        public static bool IsTokenExpired(string token)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var jwtToken = tokenHandler.ReadJwtToken(token);
                return jwtToken.ValidTo < DateTime.UtcNow;
            }
            catch
            {
                return true;
            }
        }

        /// <summary>
        /// 获取JWT令牌的过期时间
        /// </summary>
        /// <param name="token">JWT令牌字符串</param>
        /// <returns>过期时间</returns>
        public static DateTime? GetTokenExpirationTime(string token)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var jwtToken = tokenHandler.ReadJwtToken(token);
                return jwtToken.ValidTo;
            }
            catch
            {
                return null;
            }
        }
    }
} 